﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using GSF.Objects;

namespace GSF
{
    class CollisionMgr
    {
        List<Tower> m_towerList;
        List<Enemy> m_enemyList;
        static CollisionMgr m_instance;
        public static CollisionMgr Instance
        {
            get
            {
                if(m_instance == null)
                    m_instance = new CollisionMgr();
                return m_instance;
            }
        }
        CollisionMgr()
        {
        }
        public void Init(ref List<Enemy> eList, ref List<Tower> tList)
        {
            m_enemyList = eList;
            m_towerList = tList;
        }

        //collision of two objects
        public void twoObjCollision(Enemy a, Enemy b)
        {
            Random rnd = new Random();

            Vector2 distDirect = a.CenterPoint - b.CenterPoint;
            if (distDirect.Length() < a.m_desRectangle.Width/2)
            {
                if (distDirect.Length() == 0)
                {
                    //double angle = Math.PI * rnd.Next(0,180)/180;
                    //distDirect = new Vector2((float)Math.Cos(angle),(float)Math.Sin(angle));
                    b.Position += Vector2.Multiply(-b.Direction, 0.3f);
                }
                else
                {
                    distDirect.Normalize();
                    float angle = (float)Math.Acos(Vector2.Dot(a.Direction, distDirect));
                    if (angle > Math.PI / 2 && angle < Math.PI * 3 / 2)
                        return;


                    Vector2 Norm = new Vector2(-distDirect.Y, distDirect.X);

                    if (Math.Acos(Vector2.Dot(Norm, a.Direction)) > Math.PI / 2)
                        Norm *= -1;
                    a.Position += (Norm * 0.5f);
                    
                }
            }
        }

        //collision of mouse click and Objects
        public Objects.Objects getObject(Rectangle clickPoint)
        {
            foreach (Enemy e in m_enemyList)
            {
                if (e.m_desRectangle.Intersects(clickPoint))
                    return e;
            }
            foreach (Tower t in m_towerList)
            {
                if (t.m_desRectangle.Intersects(clickPoint))
                    return t;
            }
            return null;
        }
    }
}
